import sys
sys.path.append("..")


import LogModel 

import redis
import config
import json
#import commonUtil

from flask import Flask, request, jsonify
from flask_cors import CORS
import time

app = config.flaskapp


#redisDB = redis.StrictRedis(host=config.redisIp, port=config.redisPort, password=config.redisPassword, db=0)


def request_parse(request):
	#'''解析请求数据并以json形式返回'''
    if request.method == 'POST':
        data = request.form
    elif request.method == 'GET':
        data = request.args
    return data


@app.route('/')
def hello_world():
    return 'Hello Flask!'


@app.route('/uploadLogs', methods = ["POST"])
def uploadLogs():
    reqdata = request_parse(request)
    #print(f"reqdata : {reqdata}")
    appName = reqdata.get('appName')
    logsStr = reqdata.get('logs')
    logs = json.loads(logsStr)
    msg = ''

    #print(f"logs：{logs}")
    #保存数据库
    datets = time.time()
    dayString = time.strftime("%Y-%m-%d", time.localtime(datets))
    modelClass = LogModel.GetTradeLogClassWithDay(dayString, appName)

    for log in logs:
        logObj = modelClass()
        logObj.datets = int(time.time())
        logObj.Pid = log['Pid']
        logObj.logIndex = log['logIndex']
        logObj.message = log['message']
        logObj.logTime = log['logTime']

        logObj.onlySave()

    LogModel.db.session.commit()

    msg = f"保存了{len(logs)}条记录"
    retData = {'savelen':len(logs) }
    ret = {'code':0,'msg': msg, 'retData':retData}

    return jsonify(ret)


@app.route('/getLogs', methods = ["GET", "POST"])
def getLogs():
    reqdata = request_parse(request)
    #print(f"reqdata : {reqdata}")
    appName = reqdata.get('appName')
    dayString = reqdata.get('dayString')
    msg = ''

    #print(f"logs：{logs}")
    #
    time0 = time.time()
    modelClass = LogModel.GetTradeLogClassWithDay(dayString, appName)

    logs = modelClass.query.order_by(modelClass.logTime.desc())


    logArray = []
    #print('ratios:',ratios)
    if logs and logs.count() > 0:
        for r in logs:
            logArray.append(r.toJson())
    else:
        pass


    readTime = time.time() - time0
    #print(f"{modelClass.__tablename__} 数据读取时间:%.3f s  返回个数：%d"%(readTime, len(ratioArray)))


    ret = {'code':0,'data':logArray, 'readTime':readTime}

    return jsonify(ret)



# r'/*' 是通配符，让本服务器所有的 URL 都允许跨域请求
CORS(app, resources=r'/*')
if __name__ == '__main__':
    app.run(host='::', port=35500 ,threaded=True)


#  gunicorn -w 4 -t 30 -b [::]:35500 index:app

#  nohup gunicorn -w 4 -t 30 -b [::]:35500 index:app > ./logs/logserver.log 2>&1 &
